const params = new URLSearchParams(window.location.search);
const port = params.get("port") || "8000";
// 连接 websocket 服务端
const ws = new WebSocket(`ws://localhost:${port}/`);

function output(msg, type = "client") {
    const mlistDiv = document.querySelector(".message-list");
    const mitem = document.createElement("li");
    mitem.className = `message-item ${type}`;
    mitem.textContent = msg;
    mlistDiv.appendChild(mitem);
}

const poem =
    "快乐的漂泊, 在柔柔的春风中, 在柳树的绿叶中, 在布谷鸟的叫声中, 在花儿灿烂的脸上, 我们看到了美丽的春天。";
const msgList = poem.split(/,\s?/);
const delay = 1;

ws.onopen = () => {
    console.log("连接成功");

    // 发送消息
    // ws.send('hello');
    msgList.forEach((msg, i) => {
        setTimeout(() => {
            ws.send(msg);
            console.log("客户端发送消息:", msg);
            output(msg, "client");
        }, i * delay * 1000);
    });
};

ws.onmessage = async (e) => {
    // console.log(e.data); // Blob
    const msg = e.data?.text ? await e.data.text() : e.data;
    console.log("客户端收到:", msg); // Blob
    output(msg, "server");
};

ws.onclose = () => {
    console.log("连接关闭");
};

ws.onerror = () => {
    console.log("连接出错");
};

function send() {
    const inputEl = document.querySelector(".input-message");
    const msg = inputEl.value;
    if (!msg) return;
    ws.send(msg);
    output(msg, "client");
    inputEl.value = "";
    window.scrollBy(0, 1000);
}

function handleKeyup(event) {
    if (event.key === "Enter") {
        send();
    }
    // console.log("🚀 ~ handleKeyup ~ event:", event);
}
